package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.exception.BusinessException;
import com.graduation.springbootinit.mapper.BookMapper;
import com.graduation.springbootinit.model.entity.Book;
import com.graduation.springbootinit.service.BookService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 书籍服务实现类
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Resource
    private BookMapper bookMapper;

    @Override
    public long addBook(Book book) {
        if (book == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 校验参数
        validBook(book);
        boolean result = this.save(book);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return book.getId();
    }

    @Override
    public boolean deleteBook(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return this.removeById(id);
    }

    @Override
    public boolean updateBook(Book book) {
        if (book == null || book.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 校验参数
        validBook(book);
        return this.updateById(book);
    }

    @Override
    public Book getBookById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return this.getById(id);
    }

    @Override
    public List<Book> listBooks() {
        return this.list();
    }

    @Override
    public List<Book> listRecommendBooks() {
        return bookMapper.listRecommendBooks();
    }

    @Override
    public boolean batchAddBooks(List<Book> bookList) {
        if (bookList == null || bookList.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 校验参数
        for (Book book : bookList) {
            validBook(book);
        }
        return bookMapper.insertBatch(bookList) > 0;
    }

    /**
     * 校验书籍参数
     * @param book 书籍信息
     */
    private void validBook(Book book) {
        String title = book.getTitle();
        String author = book.getAuthor();
        String isbn = book.getIsbn();
        if (StringUtils.isAnyBlank(title, author, isbn)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
    }
}